package com.lpf.oauth;

import com.alibaba.fastjson.JSONObject;
import com.lpf.base.BaseApiService;
import com.lpf.utils.HttpClientUtils;
import com.lpf.utils.WeiXinUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class OauthController extends BaseApiService {

	@Autowired
	private WeiXinUtils weiXinUtils;
	private String errorPage = "errorPage";

	// 1、生成授权链接 重定向跳转到微信开放平台
	@RequestMapping("/authorizedUrl")
	public String authorizedUrl() {

		String authorizedUrl = weiXinUtils.getAuthorizedUrl();
		System.out.println(authorizedUrl);

		// 直接重定向到微信开放平台
		return "redirect:" + authorizedUrl;
	}

	// 2、用户回调地址，返回code（微信授权回调地址）
	@RequestMapping("/callback")
	@ResponseBody
	public String callback(String code, HttpServletRequest request) {

		// 1 第一步：用户同意授权，获取code
		System.out.println("code:" + code);
		if (StringUtils.isEmpty(code)) {
			return errorPage;
		}

		// 2 第二步：通过code换取网页授权access_token（调用微信接口有权限）
		String accessTokenUrl = weiXinUtils.getAccessTokenUrl(code);

		// 使用HttpClient技术调用accessTokenUrl 接口地址
		JSONObject resultAccessToken = HttpClientUtils.httpGet(accessTokenUrl);

		// 3 第三步：刷新access_token（如果需要） 判断报文中是否含有errorCode
		boolean containsKey = resultAccessToken.containsKey("errcode");
		if (containsKey) {
			request.setAttribute("errorMsg", "系统错误!");
			return errorPage;
		}

		String accessToken = resultAccessToken.getString("access_token");
		if (StringUtils.isEmpty(accessToken)) {
			// 调用接口出错
			return errorPage;
		}

		String openid = resultAccessToken.getString("openid");
		if (StringUtils.isEmpty(openid)) {
			// 调用接口出错
			return errorPage;
		}

		// 4 第四步：拉取用户信息(需scope为 snsapi_userinfo)
		String userInfoUrl = weiXinUtils.getUserInfo(accessToken, openid);
		JSONObject userInfoResult = HttpClientUtils.httpGet(userInfoUrl);

		System.out.println("userInfoResult:" + userInfoResult);

		request.setAttribute("nickname", userInfoResult.getString("nickname"));
		request.setAttribute("city", userInfoResult.getString("city"));
		request.setAttribute("headimgurl", userInfoResult.getString("headimgurl"));

		// 5、附：检验授权凭证（access_token）是否有效

		return "info";
	}

}
